package textapp.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import textapp.dao.model.Group;
import textapp.dao.model.GroupMessage;
import textapp.dao.model.GroupUser;
import textapp.dao.model.User;

public class GroupMessageDao {
	public GroupMessage create(GroupMessage gm) {
		EntityManager em = EMUtil.createEntityManager();
		em.getTransaction().begin();
		em.persist(gm);
		em.getTransaction().commit();
		em.close();
		return gm;
	}
	
	public boolean delete(int gmId) {
		boolean ret = false;
		EntityManager em = EMUtil.createEntityManager();
		em.getTransaction().begin();
		try {
			em.remove(em.find(GroupMessage.class, gmId));
			ret = true;
		} catch(Throwable t) {
			t.printStackTrace();
		}
		em.getTransaction().commit();
		em.close();
		return ret;
	}
	
	@SuppressWarnings("unchecked")
	public List<GroupMessage> getGroupMessageByGroupAndTime(int groupId, long beginTimeStampMS) {
		EntityManager em = EMUtil.createEntityManager();
		Group g = em.find(Group.class, groupId);
		if (g == null) {
			return new ArrayList<GroupMessage>();
		}
		
		Query q = em.createNamedQuery("GroupMessage.getByGroupIdAndTime");
		q.setParameter("group", g);
		q.setParameter("beginTime", new Date(beginTimeStampMS));
		return q.getResultList();		
	}
	
	@SuppressWarnings("unchecked")
	public List<GroupMessage> getGroupMessageByUserIdAndTIme(int userId, long beginTimeStampMS) {
		EntityManager em = EMUtil.createEntityManager();
		User u = em.find(User.class, userId);
		if (u == null) {
			em.close();
			return new ArrayList<GroupMessage>();
		}
		
		GroupUserDao guDao = new GroupUserDao();
		List<GroupUser> guList = guDao.getGroupUserByUserId(u.getId());
		if (guList.isEmpty()) {
			em.close();
			return new ArrayList<GroupMessage>();
		}
		StringBuilder str = new StringBuilder();
		boolean start = true;
		for (GroupUser gu : guList) {
			if (start) {
				start = false;
			} else {
				str.append(",");
			}
			str.append(gu.getGroup().getId());
		}
		String jpql = "select gm from GroupMessage gm where gm.group.id IN ("+str.toString()+")";
		jpql = jpql + " and gm.createDate > :beginTime";
		Query q = em.createQuery(jpql);
		q.setParameter("beginTime", new Date(beginTimeStampMS));
		List<GroupMessage> gmList = q.getResultList();
		em.close();
		
		return gmList;
	}
}
